/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.squirrelm.my.controller;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.squirrelm.my.domain.My;
import org.squirrelm.my.service.MyService;

/**
 *
 * @author 松鼠M
 */
@Controller
public class IndexController {

    @Autowired
    private MyService   myService;

    @RequestMapping("/index.html")
    public void aaa() {

    }

    @RequestMapping("/bbb.html")
    public @ResponseBody String bbb() {
        return "BBB";
    }

    @RequestMapping("/ccc.html")
    public @ResponseBody Object  ccc() {
        return new Date();
    }

    @RequestMapping("/ddd.html")
    public @ResponseBody Map<String,String>  ddd() {
        Map<String,String> ddd = new HashMap<String,String>();
        ddd.put("aaa", "bbb");
        return ddd;
    }

    @RequestMapping("/myCreate.html")
    public @ResponseBody String my() {
        My my = new My();
        my.setMyID(111L);
        my.setName("SquirrelM");
        myService.create(my);
        return "MY Success!";
    }

    @RequestMapping("/myGet.html")
    public @ResponseBody String myGet() {
        My my = myService.get(111L);
        return "MY name is :" + my.getName();
    }

    @RequestMapping("/testMail.html")
    public @ResponseBody String mail() throws UnsupportedEncodingException {
        testMail();
        return "Mail success!";
    }

    private void testMail() throws UnsupportedEncodingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        String msgBody = "Just test!";

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("myjkccd@gmail.com", "SquirrelM"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("myjkccd@gmail.com", "Mr. User"));
            msg.setSubject("Test GAE Mail");
            msg.setText(msgBody);
            Transport.send(msg);

        } catch (AddressException e) {
            // ...
        } catch (MessagingException e) {
            // ...
        }
    }

}
